package com.luyang.framework.lock.configuration;

import com.luyang.framework.lock.RedissonLock;
import com.luyang.framework.lock.RedissonManager;
import com.luyang.framework.lock.props.RedissonProperties;
import org.redisson.Redisson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

/**
 * Redisson 配置
 *
 * @author lu_yang
 */
@Configuration
@ConditionalOnClass(Redisson.class)
@EnableConfigurationProperties(RedissonProperties.class)
@ConditionalOnProperty(prefix = "luyang.lock", name = "enable", havingValue = "true")
public class RedissonConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(RedissonConfiguration.class);

    @Order(value = 2)
    @ConditionalOnMissingBean
    @ConditionalOnBean(RedissonManager.class)
    public @Bean RedissonLock redissonLock(RedissonManager redissonManager) {
        var redissonLock = new RedissonLock();
        redissonLock.setRedissonManager(redissonManager);
        logger.info("RedissonLock 构建完成");
        return redissonLock;
    }

    @Order(value = 1)
    @ConditionalOnMissingBean
    public @Bean RedissonManager redissonManager(RedissonProperties redissonProperties) {
        RedissonManager redissonManager = null;
        try {
            redissonManager = new RedissonManager(redissonProperties);
            logger.info("RedissonManager组装完毕,当前连接方式:{},连接地址:{}", redissonProperties.getType(), redissonProperties.getAddress());
        } catch (Exception e) {
            logger.error("Redisson 初始化失败", e);
        }

        return redissonManager;
    }
}
